#!/usr/bin/php
<?php
	require_once('config.php');
	require_once('include/lsamp_curl.php');
	include("include/phpMailer/class.phpmailer.php");

	error_reporting($error_display);
	date_default_timezone_set($timezone);
	// start logging
	error_log(date("d/m/y H:i:s") . " | " . "***Begin transation***\n",3,$log_file);
	//load data from the .dat file
	$max_prev_timestamp = 0;
	$info = "";
	if(file_exists($dat_file)){
		$info = file_get_contents($dat_file);
		$matched = preg_match('/max_prev_timestamp=(\d+)/', $info, $matches);
		if($matched){
			$max_prev_timestamp = $matches[1];
		}else{
			$info .= "max_prev_timestamp=0";
			error_log(date("d/m/y H:i:s") . " | " ."Can't find the max previous timestamp in the .dat file, write a new one \n", 3, $log_file);
		}
	}

	//log in the RAC
	$post_data = 'txtReturnURL=' . $return_url;
	$post_data .= '&lngWId=1';
	$post_data .= '&blnOutsideOfVBSubWeb=false';
	$post_data .= '&strPassKey=';
	$post_data .= '&txtEmailAddress=' . urlencode($account['email']);
	$post_data .= '&txtPassword=' . $account['password'];
	$post_data .= '&chkRememberPassword=TRUE';
	$post_data .= '&cmOk=Ok';
	$rac_client = new lsamp_cURL(TRUE, $cookie_file, 'gzip', '', $base_url,20);
	// login the rac site
	$result = $rac_client->post($login_url, $post_data, $errno, $error);
	if($errno != 0){
		error_log(date("d/m/y H:i:s") . " | " . "Error: " . $error . "\n",3,$log_file);
		exit;
	}else{
		error_log(date("d/m/y H:i:s") .  " | " ."Login information posted \n" , 3, $log_file);
	}
	// follow the ridirect link
	$matched = preg_match('/lngIdentId=(\d+)/', $result, $match);
	if(!$matched){
		error_log(date("d/m/y H:i:s") .  " | " ."Document format changed \n", 3, $log_file);
		exit;
	}else{
		$login_redirect_url .= $match[1];
	}
	$result = $rac_client->get($login_redirect_url, $errno, $error);
	if($errno != 0){
                error_log(date("d/m/y H:i:s") .  " | " ."Error: " . $error . "\n",3,$log_file);
                exit;
        }else{
                error_log(date("d/m/y H:i:s") .  " | " ."Logged in with the cookie file is " . basename($cookie_file) ." \n" , 3, $log_file);
        }
	//echo $result; exit;
	// fetch the newest open bids page
	$result = $rac_client->get($newest_bids_url, $errno, $error);
	if($errno != 0){
		error_log(date("d/m/y H:i:s") .  " | " ."Error occurred when fetching the newest open bids: " . $error . "\n",3,$log_file);
		exit;
	}else{
		error_log(date("d/m/y H:i:s") .  " | " ."Newest open bids fetched.\n" , 3, $log_file);
	}
	$dom = new DOMDocument();
	$result = str_replace("&nbsp;", " ", $result);
	@$dom->loadHTML($result); //load the html to a dom tree
	$dom->preserveWhiteSpace = false;
	$tableset = $dom->getElementsByTagName("table"); // get all tables
	foreach($tableset as $table){
		if($table->getAttribute('width') == "90%" && $table->getAttribute('cellspacing') == "0"){ // get the table which has width = 90%
			break;
		}else{
			continue;
		}
	}
	$rowset = $table->getElementsByTagName("tr");
	$count = 0;
	$jobs = array();
	$max_timestamp = 0;
	//echo $rowset->length; exit;
	for(;4* $count + 6 < $rowset->length; $count ++){
		$job = array();
		// abort the first row which contains column titles
//		if($count == 0){
//			continue;
//		}
		// process a group of two rows
		$info_row = $rowset->item(4* $count + 2);
		$columns = $info_row->getElementsByTagName("td");
		for($i=0; $i< $columns->length; $i++){
			$column = $columns->item($i);
			if($i == 1){ // get link, title and author from the first column
				$anchors = $column->getElementsByTagName('a');
				$job['link'] = $base_url . $anchors->item(0)->getAttribute('href');
				if(!empty($job['link'])){
					$matched = preg_match('/lngBidRequestId=(\d+)/', $job['link'], $match);
					if($matched){
						$job['id'] = $match[1];
					}else{
						$job['id'] = -1;
					}
				}
				$job['title'] = $anchors->item(0)->nodeValue;
				$job['title'] = trim($job['title']);
				$job['author'] = $anchors->item(1)->nodeValue;
				$job['author_detail_link'] = $base_url . $anchors->item(1)->getAttribute('href');
				$job['author_rating'] = $anchors->item(2)->nodeValue;
				$job['author_rating_link'] = $base_url . $anchors->item(2)->getAttribute('href');
				$job['author'] = trim($job['author']);
				$job['author_rating'] = trim($job['author_rating']);
			}
			if($i == 2){ // get project type, category from the second column
				$tmp = array();
				$text = $column->nodeValue;
				$tmp = split("\n",$text);
				$job['project_type'] = trim($tmp[0]);
				$job['category'] = trim($tmp[1]);
			}
			if($i == 3){ // get bid phrase, and max bid
				$tmp = array();
				$text = $column->nodeValue;
				$tmp = split("Max bid:",$text);
				$job['phrase'] = trim($tmp[0]);
				$job['max_bid'] = trim($tmp[1]);
			}
			if($i == 4){ // get bid phrace, and max bid
				$tmp = array();
				$text = $column->nodeValue;
				$tmp = split("since",$text);
				$job['views'] = trim($tmp[0]);
				$job['date'] = trim($tmp[1]);
				if(strtotime($job['date']) <= $max_prev_timestamp){
					break;
				}
			}
		}
		if($i <  $columns->length ) break;
		$desc_row = $rowset->item(4 * $count + 4);
		$job['description'] = trim($desc_row->nodeValue);
		array_push($jobs, $job);

	}
	if(count($jobs) > 0){

		$max_timestamp = strtotime($jobs[0]['date']);
		//write the max got job id to the .dat file
		$fd = fopen($dat_file, "w");
		if($info !== ""){
			$info = preg_replace('/max_prev_timestamp=\d+/', "max_prev_timestamp=" . $max_timestamp, $info);
			if($info == NULL){
				error_log(date("d/m/y H:i:s") .  " | " ."There is an error occurred " . __FILE__ . ": " . __LINE__ . "\n", 3, $log_file);
			}else{
				error_log(date("d/m/y H:i:s") .  " | " ."Wrote timestamp: $max_timestamp to the data file\n", 3, $log_file);
				fwrite($fd, $info);
			}
		}else{
			$info .= "max_prev_timestamp=" . $max_timestamp;
			fwrite($fd, $info);
		}
		fclose($fd);
		//write to a dump file
		$fd = fopen($dump_file, "w");
		fwrite($fd, jobs_to_html($jobs));
		fclose($fd);
		send_mail($alert_agent, jobs_to_html($jobs), count($jobs), $alert_receivers, $log_file);

	}else{
		error_log(date("d/m/y H:i:s") . " | " . "There is not any new job\n",3,$log_file);
	}
	error_log(date("d/m/y H:i:s") . " | " . "***End transation***\n",3,$log_file);

	function job_to_txt($myjob){
		$text = "----------------------------------------";
		foreach(array_keys($myjob) as $key){
			$text .= "$key:" . $myjob[$key] ."\n";
		}
		$text .= "---------------------------------------";
		return $text;
	}

	function job_to_html($myjob){
		$html = "<tr><td colspan=\"3\" align=\"center\">-------</td></tr>";
		$html .= "<tr>";
		$html .= "<td colspan=\"3\" align=\"center\"><b><a href=\"" . $myjob['link'] ."\">" . $myjob['title'] . "</a></b></td></tr>\n";
		$html .= "<tr><td colspan=\"3\" align=\"center\"><b><a href=\"" . $myjob['link'] ."\">" . $myjob['link'] . "</a></b></td></tr>\n";
		$html .= "<tr><td align=\"right\" valign=\"top\" width=\"35%\"><b>DESCRIPTION:</b></td><td width=\"5%\"></td><td align=\"left\"><i>" . $myjob['description'] ."</i></td></tr>";
		$html .= "<tr><td align=\"right\" valign=\"top\" width=\"35%\"><b>MAX BID:</b></td><td width=\"5%\"></td><td align=\"left\"><i>" . $myjob['max_bid'] ."</i></td></tr>";
		$html .= "<tr><td align=\"right\" valign=\"top\" width=\"35%\"><b>AUTHOR:</b></td><td width=\"5%\"></td><td align=\"left\"><i><a href=\"" . $myjob['author_detail_link'] . "\">" . $myjob['author'] ."</a>(<a href=\"" . $myjob['author_rating_link'] . "\">" . $myjob['author_rating'] . "</a>)</i></td></tr>";
		foreach(array_keys($myjob) as $key){
			if($key == 'title' || $key == 'id' || $key == 'link' || $key == 'description' || $key == 'max_bid' || $key == 'author' || $key == 'author_rating' || $key == 'author_rating_link' || $key == 'author_detail_link') continue;
			$html .= "<tr><td align=\"right\" valign=\"top\" width=\"35%\"><b>" . strtoupper($key) . ":</b></td><td width=\"5%\"></td><td align=\"left\"><i>" . $myjob[$key] ."</i></td></tr>";
		}
		return $html;
	}

	function jobs_to_html($myjobs){
		$html = "<table align=\"center\" width=\"100%\" cellspacing=\"25\">";
		foreach($myjobs as $job){
			$html .= job_to_html($job);
		}
		$html .= "</table>";
		return $html;
	}

	function send_mail($agent, $content, $number_of_content_items, $receivers, $mail_log_file){

		$mail             = new PHPMailer();
		$body             = $content;
		$mail->IsSMTP();
		$mail->SMTPAuth   = true;                  // enable SMTP authentication
		$mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
		$mail->SMTPDebug = $agent['smtp_debug'];   // debug the smtp server
		$mail->Host       = $agent['smtp_host'];      // sets GMAIL as the SMTP server
		$mail->Port       = $agent['smtp_port'];                   // set the SMTP port for the GMAIL server

		$mail->Username   = $agent['smtp_user'];  // GMAIL username
		$mail->Password   = $agent['smtp_pass'];  // GMAIL password

		$mail->From       = $agent['from'];
		$mail->FromName   = $agent['from_name'];
		$mail->Timeout	  = $agent['timeout'];
		$mail->Subject    = $agent['subject'] . " " . $number_of_content_items . (($number_of_content_items > 1)?" bids":" bid") . " " . date("H:i d/m/y");

		$mail->IsHTML(true); // send as HTML
		$mail->Body = $body;
		$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
		$mail->WordWrap   = 50; // set word wrap

		for($i=0; $i< count($receivers); $i++){
			$mail->AddAddress($receivers[$i]['addr'],$receivers[$i]['name']);
		}
		//$mail->MsgHTML($body);

		//var_dump($mail); exit;
		if(!$mail->Send()) {
		  error_log(date("d/m/y H:i:s") .  " | " ."Mailer Error: " . $mail->ErrorInfo . "\n", 3, $mail_log_file);
		} else {
		  error_log(date("d/m/y H:i:s") .  " | " ."Mail sent \n", 3, $mail_log_file);
		}
	}

?>
